export class CacheManager {
    constructor() { }
    /**
     * CacheManager的单例
     */
    static Current: CacheManager = new CacheManager();

    /**
     * 缓存对象集合
     */
    private list: ICacheMember[] = [];

    /**
     * 添加某项缓存
     * @param  {ICacheMember} member 要缓存的对象
     */
    add(member: ICacheMember) {
        let flag = false;
        //update
        for (let i = 0; i < this.list.length; i++) {
            if (this.list[i].key == member.key) {
                this.list[i] = member;
                flag = true;
                break;
            }
        }
        if (!flag) {
            this.list.push(member);
        }
    }

    /**
     * 获取某项缓存
     * @param  {string} key
     */
    get(key: string) {
        let result =  this.list.find(item => {
            return item.key == key;
        });
        if (!result) {
            return null;
        }
        return result.value;
    }

    /**
     * 清空缓存
     */
    clear() {
        this.list = [];
    }

    /**
     * 删除某项缓存
     * @param  {string} key
     */
    delete(key: string) {
        let del = null;
        for (let i = 0; i < this.list.length; i++) {
            if (this.list[i].key == key) {
                del = this.list.splice(i, 1);
                break;
            }
        }
        return del;
    }

    /**
     * 是否被缓存
     * @param  {string} key
     */
    isCached(key: string) {
        let flag = false;
        let result = this.list.find(item => {
            return item.key == key;
        });
        if (result) {
            flag = true;
        }
        return flag;
    }
}

export interface ICacheMember {
    key: string;
    value: any;
}